package com.betterman.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.betterman.depend.idworker.Sid;
import com.betterman.mapper.UserMapper;
import com.betterman.pojo.User;
import com.betterman.pojo.bo.RegisterUserBO;
import com.betterman.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fox
 * @since 2020-08-05
 */
@Service
public class UserServiceImpl implements UserService {
    /**
     * Twitter idworker 生成顺序ID
     */
    @Autowired
    private Sid sid;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户是否存在
     *
     * @param username 用户名
     * @return {boolean}
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    @Override
    public boolean queryUserIsExists(String username) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        User user = userMapper.selectOneByExample(example);
        return user != null;
    }

    /**
     * 保存注册用户信息
     *
     * @param registerUserBO 注册用户信息
     * @return 注册成功的用户信息
     * @author <a href="mailto:foxfocus@163.com">fox</a>
     */
    @Override
    public User saveRegisterUser(RegisterUserBO registerUserBO) {
        User user = new User();
        user.setUsername(registerUserBO.getUsername());
        user.setPassword(SecureUtil.md5(registerUserBO.getPassword()));
        user.setCreated(LocalDateTime.now());
        user.setId(sid.nextShort());
        userMapper.insert(user);
        return user;
    }

    @Override
    public User loginRegister(RegisterUserBO registerUserBO) {
        User user = new User();
        user.setUsername(registerUserBO.getUsername());
        user.setPassword(SecureUtil.md5(registerUserBO.getPassword()));
        List<User> users = userMapper.select(user);
        // 未查询到对应的用户信息
        if (CollectionUtils.isEmpty(users) || users.get(0) == null) {
            return null;
        }
        // 更新登录时间
        User loginUser = users.get(0);
        loginUser.setLasted(LocalDateTime.now());
        userMapper.updateByPrimaryKey(loginUser);
        return loginUser;
    }
}
